<script setup lang="ts">

const tableData = ref([])


import {ref, onMounted} from 'vue'
import {ComponentSize, ElMessageBox, ElMessage} from 'element-plus'
import {getUserBorrow, sendOverdueEmail, returnBook} from '@/api/admin'

const currentPage4 = ref(1)
const pageSize4 = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const total = ref(0)
const status = ref('')

//获取用户借阅历史的请求参数
const getUserBorrowDTO = ref({
  pageNumber: 1,
  pageSize: 10,
  username: '',
  status: ''
})

//调用接口获取数据
const getUserBorrowing = async () => {
  getUserBorrowDTO.value.pageNumber = currentPage4.value
  getUserBorrowDTO.value.pageSize = pageSize4.value
  getUserBorrowDTO.value.username = input.value
  getUserBorrowDTO.value.status = status.value
  const res = await getUserBorrow(getUserBorrowDTO.value)
  total.value = res.data.total
  tableData.value = res.data.results
}

//每页条数发生变化
const handleSizeChange = (val: number) => {
  getUserBorrowDTO.value.pageNumber = val
  getUserBorrowing()
  console.log(`${val} items per page`)
}

//当前页码发生变化
const handleCurrentChange = (val: number) => {
  getUserBorrowDTO.value.pageSize = val
  getUserBorrowing()
  console.log(`current page: ${val}`)
}

//搜索
const onSubmit = () => {
  getUserBorrowing()
}

//重置
const reset = () => {
  input.value = ''
  status.value = ''
  getUserBorrowing()
}

const input = ref('')

//状态选择器
const options = [
  {
    value: '借阅中',
    label: '借阅中',
  }, {
    value: '已归还',
    label: '已归还',
  }
]

// 添加计算序号的方法
const getIndex = (index: number) => {
  return (currentPage4.value - 1) * pageSize4.value + index + 1
}

onMounted(() => {
  getUserBorrowing()
})

//详情查看
const detail = (row) => {
  dialogVisible.value = true
  getUserBorrowDetail.value = row
  console.log(row)
}

//详情弹窗

const dialogVisible = ref(false)
const getUserBorrowDetail = ref<any>(null)

//续租
const handleRenew = (row) => {
  console.log('续租', row)
  // TODO: 调用续租接口
}

//发送邮件提醒
const handleRemind = async (row) => {
  try {
    // 直接传递 borrowHistoryId 字符串
    await sendOverdueEmail(row.borrowHistoryId.toString())
    ElMessage.success('已发送逾期提醒邮件')
  } catch (error) {
    ElMessage.error('发送提醒失败')
  }
}

// 加状态标签类型判断方法
const getStatusType = (status: string) => {
  switch (status) {
    case '借阅中':
      return 'warning'
    case '已归还':
      return 'success'
    default:
      return 'info'
  }
}

//归还图书
const handleReturn = async (row) => {
  try {
    await ElMessageBox.confirm('确认用户已归还这本图书了吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await returnBook(row.borrowHistoryId.toString())
    ElMessage.success('图书归还成功')
    getUserBorrowing() // 刷新列表
    dialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('归还失败')
    }
  }
}

</script>

<template>

  <!-- 用户借阅历史列表 -->
  <el-card>
    <div class="card-header">
      <span>用户借阅历史列表</span>
    </div>
    <el-divider/>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="input" style="width: 240px" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item>
        <el-select
            v-model="status"
            clearable
            placeholder="请选择申请状态"
            style="width: 240px"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="序号" width="80">
        <template #default="{ $index }">
          {{ getIndex($index) }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="title" label="书名"/>
      <el-table-column prop="borrowDate" label="借阅时间"/>
      <el-table-column prop="status" label="借阅状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="操作" width="180">
        <template #default="{ row }">
          <el-button type="danger" plain @click="detail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
          class="el-p"
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :page-sizes="[10, 15, 20, 25]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="jumper, total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 详情弹窗 -->
  <el-dialog v-model="dialogVisible" title="借阅详情" width="40%">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="书名">{{ getUserBorrowDetail.title }}</el-descriptions-item>
      <el-descriptions-item label="用户名">{{ getUserBorrowDetail.username }}</el-descriptions-item>
      <el-descriptions-item label="借阅时间">{{ getUserBorrowDetail.borrowDate }}</el-descriptions-item>
      <el-descriptions-item label="应还时间">{{ getUserBorrowDetail.dueDate }}</el-descriptions-item>
      <el-descriptions-item label="归还时间">{{ getUserBorrowDetail.returnDate || '-' }}</el-descriptions-item>
      <el-descriptions-item label="逾期天数">
        <el-tag type="danger" v-if="getUserBorrowDetail.overdueDays">{{ getUserBorrowDetail.overdueDays }}天</el-tag>
        <span v-else>-</span>
      </el-descriptions-item>
      <el-descriptions-item label="审核状态">
        <el-tag :type="getUserBorrowDetail.status === '已通过' ? 'success' : 'warning'">
          {{ getUserBorrowDetail.status }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="审核人">{{ getUserBorrowDetail.adminName }}</el-descriptions-item>
      <el-descriptions-item label="审核时间">{{ getUserBorrowDetail.reviewDate }}</el-descriptions-item>
      <el-descriptions-item label="备注">{{ getUserBorrowDetail.comments || '-' }}</el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button 
          type="success" 
          @click="handleReturn(getUserBorrowDetail)"
          v-if="getUserBorrowDetail && getUserBorrowDetail.status === '借阅中'">
          用户归还图书
        </el-button>
        <el-button type="primary" @click="handleRenew(getUserBorrowDetail)">
          续租
        </el-button>
        <el-button type="warning" @click="handleRemind(getUserBorrowDetail)"
                   :disabled="!getUserBorrowDetail.overdueDays">
          逾期提醒
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped lang="scss">

.el-p {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
}
</style>